package com.example.myapplication.ui

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.bun.miitmdid.interfaces.IPermissionCallbackListener
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.CSJAdError
import com.bytedance.sdk.openadsdk.CSJSplashAd
import com.bytedance.sdk.openadsdk.CSJSplashAd.SplashAdListener
import com.bytedance.sdk.openadsdk.TTAdNative.CSJSplashAdListener
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.example.myapplication.App.Companion.context
import com.example.myapplication.R
import com.example.myapplication.ad.AdManager.Companion.getCodeId
import com.example.myapplication.ad.Location
import com.example.myapplication.ad.TTAdManagerHolder
import com.example.myapplication.appViewModel
import com.example.myapplication.databinding.ActivitySplashBinding
import com.example.myapplication.network.LaunchInfo
import com.example.myapplication.utils.DemoHelper
import com.example.myapplication.utils.DisplayUtils
import com.example.myapplication.utils.SPUtils
import com.example.myapplication.view.CommonDialog
import com.example.myapplication.viewmodel.ApiViewModel
import kotlinx.parcelize.Parcelize

@Parcelize
data class VideoFolder(
    val path: String,
    val name: String,
    var count: Int,
    val thumbnailUri: Uri?,
    val videos: ArrayList<VideoItem> = arrayListOf()
) : Parcelable

@Parcelize
data class VideoItem(
    val id: String,
    val uri: Uri?, val name: String?, val duration: Long, val size: Long, val path: String?,
    val resolution: String?
) : Parcelable


class SplashActivity : AppCompatActivity(), DemoHelper.AppIdsUpdater {
    private val TAG = "SplashActivity"
    private lateinit var binding: ActivitySplashBinding
    private val viewModel by viewModels<ApiViewModel>()
    private lateinit var demoHelper: DemoHelper
    private var mCsjSplashAd: CSJSplashAd? = null
    private var isFirst = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivitySplashBinding.inflate(layoutInflater)
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        setupObservers()

        if (!SPUtils.hasPrivacy()) {
            CommonDialog.show(
                context = this,
                config = CommonDialog.Config(
                    icon = ContextCompat.getDrawable(this, R.mipmap.icon),
                    content = getString(R.string.privacy),
                    positiveText = "同意",
                    negativeText = "不同意",
                    cancelable = false,
                    onNegativeClick = {
                        finish()
                    },
                    onPositiveClick = {
                        SPUtils.setPrivacy(true)
                        init(true)
                    }
                )
            )
        } else {
            init(false)
        }
    }

    private fun init(isFirst: Boolean) {
        demoHelper = DemoHelper(this, "msaoaidsec")
        demoHelper.getDeviceIds(this)
        // requestPermissionX()
        viewModel.loadImage()
    }

    private fun setupObservers() {
        appViewModel.launchData.observe(this) {
            if (it == null || !isFirst) {
                return@observe
            }
            isFirst = false
            context.initAdSdk(object : TTAdManagerHolder.OnAdInitListener {
                override fun onInitSuccess() {
                    showAD()
                }

                override fun onInitFailed() {
                    goToMainActivity()
                }
            })
        }
        viewModel.error.observe(this) { error ->
            goToMainActivity()
        }
    }

    override fun onIdsValid(ids: String?) {
        SPUtils.setKeyValue("oaid", ids?.replace("\"", ""))
        requestOaidPermission()
    }

    private fun requestOaidPermission() {
        if (demoHelper.isSupported) {
            if (demoHelper.isLimited) {
                // 如果支持请求OAID获取权限，就请求权限
                if (demoHelper.isSupportRequestOAIDPermission) {
                    demoHelper.requestOAIDPermission(this, object : IPermissionCallbackListener {
                        // 获取授权成功
                        override fun onGranted(grPermission: Array<String?>?) {
                            demoHelper.getDeviceIds(this@SplashActivity)
                        }

                        // 获取授权失败
                        override fun onDenied(dePermissions: MutableList<String?>?) {
                            // 处理代码
                        }

                        // 禁止再次询问
                        override fun onAskAgain(asPermissions: MutableList<String?>?) {
                            // 处理代码
                        }
                    })
                }
            }
        }
    }

    private fun showAD() {
        val ad: LaunchInfo.AdSlot? = getCodeId(Location.A10001)
        if (ad == null || !ad.state || !TTAdSdk.isSdkReady()) {
            goToMainActivity()
            return
        }
        val adNativeLoader = TTAdManagerHolder.get()?.createAdNative(this)
        val adSlot = AdSlot.Builder()
            .setCodeId(ad.stubId)
            .setImageAcceptedSize(DisplayUtils.getWidth(context), DisplayUtils.getHeight(context))
            .build()
        adNativeLoader?.loadSplashAd(adSlot, object : CSJSplashAdListener {
            override fun onSplashRenderSuccess(csjSplashAd: CSJSplashAd) {
                /** 渲染成功后，展示广告  */
                Log.i(TAG, "onSplashRenderSuccess")
                showSplashAd(csjSplashAd)
            }

            override fun onSplashLoadSuccess(p0: CSJSplashAd?) {
                Log.i(TAG, "onSplashLoadSuccess")
            }

            override fun onSplashLoadFail(csjAdError: CSJAdError?) {
                /**仅CSJ
                 * csjAdError.getCode() == 1，物料加载失败
                 *
                 * csjAdError.getCode() == 2，素材加载失败
                 *
                 * csjAdError.getCode() == 3，渲染失败、渲染超时
                 *
                 * csjAdError.getCode() == 23，加载超时
                 *
                 */
                Log.i(TAG, "onSplashLoadFail: msg[${csjAdError?.msg}]  code[msg[${csjAdError?.code}]]")
            }

            override fun onSplashRenderFail(csjSplashAd: CSJSplashAd?, csjAdError: CSJAdError?) {
                Log.i(TAG, "onSplashRenderFail: msg[${csjAdError?.msg}]  code[msg[${csjAdError?.code}]]")
                goToMainActivity()
            }
        }, 3500)

    }

    fun showSplashAd(csjSplashAd: CSJSplashAd) {
        mCsjSplashAd = csjSplashAd
        csjSplashAd.setSplashAdListener(object : SplashAdListener {
            override fun onSplashAdShow(csjSplashAd: CSJSplashAd?) {
                Log.i(TAG, "onSplashAdShow")
            }

            override fun onSplashAdClick(csjSplashAd: CSJSplashAd?) {
                Log.i(TAG, "onSplashAdClick")
            }

            override fun onSplashAdClose(csjSplashAd: CSJSplashAd?, closeType: Int) {
                // 广告关闭后，销毁广告页面
                Log.i(TAG, "onSplashAdClose")
                goToMainActivity()
            }
        })
        val splashView = csjSplashAd.getSplashView()
        DisplayUtils.removeFromParent(splashView)
        binding.splashContainer.apply {
            removeAllViews()
            addView(splashView)
        }
    }

    private fun goToMainActivity() {
        val intent = Intent(context, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
        finish()


     //   startActivity(Intent(this,MainActivity::class.java))

    }

    override fun onDestroy() {
        super.onDestroy()
        mCsjSplashAd?.mediationManager?.destroy()
    }
}